package assists.caches
{
	import assists.URI;
	import assists.log.Log;
	import assists.resource.ResourceLoader;
	
	import com.coltware.airxzip.ZipEntry;
	import com.coltware.airxzip.ZipFileReader;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	public class SaveZipAsFile
	{
		private var progressFunc:Function;
		private var loadSuccessFunc:Function;
		
		private var urlLoader:URLLoader;
		
		private var _saveImage:SaveImage;
		
		private var fileName:String;
		private var index:int = 0;
		private var reader:ZipFileReader;
		private var _unzipAddress:String = "";
		
		private var saveFile:File;
		private var _onUnzipsuccess:Function;
		
		
		public function SaveZipAsFile()
		{
			urlLoader = new URLLoader;
			
			_saveImage = new SaveImage;
		}	
		
		public function set loadProgress(func:Function):void
		{
			progressFunc = func;
		}
		
		public function set loadSuccess(func:Function):void
		{
			loadSuccessFunc = func;
		}
		
		public function clear():void
		{
			index = 0;
			saveFile = null;
			
			//			deleteZip();
		}
		
		
		public function unzip_init(filename:String,type:int = 1,url:String = ""):void
		{
			_unzipAddress = url;
			urlLoader.addEventListener(Event.COMPLETE,completeHandler);
			urlLoader.addEventListener(ProgressEvent.PROGRESS,progressHandler);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
			
			urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
			urlLoader.load(new URLRequest(filename));
			
			if(type == 1){
				fileName = filename.split("/")[8];
			}else{
				fileName = filename.split("/")[9];
			}
		}
		
		protected function errorHandler(event:IOErrorEvent):void
		{
			trace("error");
		}
		
		protected function progressHandler(e:ProgressEvent):void
		{
			if(progressFunc is Function){
				progressFunc(e.bytesLoaded * .99 ,e.bytesTotal);
			}
			
			if(e.bytesLoaded == e.bytesTotal){
				if(loadSuccessFunc != null) loadSuccessFunc();
			}
		}
		
		public function set unzipSuccess(value:Function):void
		{
			_onUnzipsuccess = value;
		}
		
		protected function completeHandler(e:Event):void
		{
			urlLoader.removeEventListener(Event.COMPLETE,completeHandler);
			urlLoader.removeEventListener(ProgressEvent.PROGRESS,progressHandler);
			urlLoader.removeEventListener(IOErrorEvent.IO_ERROR,errorHandler);
			
			saveFile = File.documentsDirectory.resolvePath("iWeiHai" + _unzipAddress);
			if(saveFile.exists == false)
			{
				saveFile.createDirectory();
			}
			
			var fs:FileStream = new FileStream();
			fs.open(new File(saveFile.resolvePath(fileName).nativePath),FileMode.WRITE);
			fs.writeBytes(urlLoader.data);
			fs.close();
			
			reader = new ZipFileReader();
			var zipfile:File = saveFile.resolvePath(fileName);
			reader.open(zipfile);
			
			var list:Array = reader.getEntries();
			
			trace(list);
			
			index = 0;
			doWithZipFile(list);
			if(_onUnzipsuccess != null)
			{
				_onUnzipsuccess();
				_onUnzipsuccess = null;
			}
		}
		
		private function doWithZipFile(list:Array):void
		{
			var zipFile:ZipEntry = list[index];
			
			if(zipFile.isDirectory()){
				trace("DIR  --->" + zipFile.getFilename());
				
				if(index + 2 <= list.length){
					index++;
					doWithZipFile(list);
					
					if(progressFunc is Function){
						progressFunc(index,list.length - 1);
					}
				}
			}
			else{
				trace("FILE --->" + zipFile.getFilename() + "(" + zipFile.getCompressRate() + ")");
				
				var byteArray:ByteArray = reader.unzip(zipFile);
				var name:String = zipFile.getFilename();
				
				if(name.indexOf(".xml")){
					_saveImage.saveXML(byteArray,new File(saveFile.resolvePath(name).nativePath),name);
					
					if(index + 2 <= list.length){
						index++;
						doWithZipFile(list);
						
						if(progressFunc is Function){
							progressFunc(index,list.length - 1);
						}
					}
					
					return;
				}else{
					var _loader:Loader = new Loader;
					_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,saveHandler);
					_loader.loadBytes(byteArray);
				}
				
				function saveHandler(e:Event):void
				{	
					_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,saveHandler);
					
					if(index + 2 <= list.length){
						index++;
						doWithZipFile(list);
						
						if(progressFunc is Function){
							progressFunc(index,list.length - 1);
						}
					}
					
					if(name.indexOf("png") && name.indexOf("jpg") == -1){
						
						var img1:Bitmap = _loader.content as Bitmap
						_saveImage.savePng(img1.bitmapData.clone(),new File(saveFile.resolvePath(name).nativePath),name);
						return;
					}
					
					if(name.indexOf("jpg") && name.indexOf("png") == -1){
						
						var img2:Bitmap = _loader.content as Bitmap
						_saveImage.saveJpg(img2.bitmapData.clone(),new File(saveFile.resolvePath(name).nativePath),name);
						return;
					}		
				}
				
			}
		}		
		private function deleteZip():void
		{
			var file:File = File.documentsDirectory.resolvePath("iWeiHai/" + fileName);
			file.deleteFile();
			file = null;
		}
	}
}
